const axios = require('axios');
require('dotenv').config();

class EduSystemClient {
  constructor() {
    this.apiKey = process.env.EDU_API_KEY;
    this.baseURL = process.env.EDU_API_BASE_URL;
    this.client = axios.create({
      baseURL: this.baseURL,
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json'
      },
      timeout: 10000 // 10秒超时
    });
  }

  /**
   * 获取课程大纲和知识点树
   * @param {number} courseId - 课程ID
   * @returns {Promise<object>} - 课程大纲和知识点树
   */
  async getCourseOutline(courseId) {
    try {
      const response = await this.client.get(`/courses/${courseId}/outline`);
      return response.data;
    } catch (error) {
      console.error('获取课程大纲失败:', error.message);
      if (error.response) {
        console.error('响应状态:', error.response.status);
        console.error('响应数据:', error.response.data);
      }
      
      // 如果教务系统API不可用，返回模拟数据
      return this.getMockCourseOutline(courseId);
    }
  }

  /**
   * 获取学生学情数据
   * @param {number} courseId - 课程ID
   * @param {number} [classId] - 班级ID，可选
   * @returns {Promise<object>} - 学生学情数据
   */
  async getStudentLearningStatus(courseId, classId = null) {
    try {
      let url = `/courses/${courseId}/learning-status`;
      if (classId) {
        url += `?classId=${classId}`;
      }
      const response = await this.client.get(url);
      return response.data;
    } catch (error) {
      console.error('获取学生学情数据失败:', error.message);
      if (error.response) {
        console.error('响应状态:', error.response.status);
        console.error('响应数据:', error.response.data);
      }
      
      // 如果教务系统API不可用，返回模拟数据
      return this.getMockStudentLearningStatus(courseId, classId);
    }
  }

  /**
   * 获取知识点详情
   * @param {number} knowledgePointId - 知识点ID
   * @returns {Promise<object>} - 知识点详情
   */
  async getKnowledgePointDetail(knowledgePointId) {
    try {
      const response = await this.client.get(`/knowledge-points/${knowledgePointId}`);
      return response.data;
    } catch (error) {
      console.error('获取知识点详情失败:', error.message);
      if (error.response) {
        console.error('响应状态:', error.response.status);
        console.error('响应数据:', error.response.data);
      }
      
      // 如果教务系统API不可用，返回模拟数据
      return this.getMockKnowledgePointDetail(knowledgePointId);
    }
  }

  /**
   * 获取课程教学资源
   * @param {number} courseId - 课程ID
   * @returns {Promise<object>} - 课程教学资源
   */
  async getCourseResources(courseId) {
    try {
      const response = await this.client.get(`/courses/${courseId}/resources`);
      return response.data;
    } catch (error) {
      console.error('获取课程教学资源失败:', error.message);
      if (error.response) {
        console.error('响应状态:', error.response.status);
        console.error('响应数据:', error.response.data);
      }
      
      // 如果教务系统API不可用，返回模拟数据
      return this.getMockCourseResources(courseId);
    }
  }

  // 以下是模拟数据方法，用于在教务系统API不可用时提供测试数据

  /**
   * 获取模拟课程大纲
   * @param {number} courseId - 课程ID
   * @returns {object} - 模拟课程大纲
   */
  getMockCourseOutline(courseId) {
    return {
      courseId,
      courseName: '示例课程',
      totalHours: 48,
      credit: 3,
      knowledgeTree: [
        {
          id: 101,
          name: '第一章 基础概念',
          parentId: null,
          children: [
            {
              id: 1011,
              name: '1.1 核心术语定义',
              parentId: 101,
              importance: 8,
              difficulty: 'medium'
            },
            {
              id: 1012,
              name: '1.2 基本原理',
              parentId: 101,
              importance: 9,
              difficulty: 'hard'
            }
          ]
        },
        {
          id: 102,
          name: '第二章 应用技术',
          parentId: null,
          children: [
            {
              id: 1021,
              name: '2.1 技术实现',
              parentId: 102,
              importance: 7,
              difficulty: 'medium'
            },
            {
              id: 1022,
              name: '2.2 案例分析',
              parentId: 102,
              importance: 6,
              difficulty: 'easy'
            }
          ]
        }
      ],
      teachingEmphasis: [
        { id: 1012, name: '1.2 基本原理', reason: '理论基础，是后续章节的前提' },
        { id: 1021, name: '2.1 技术实现', reason: '实践应用，是课程的核心内容' }
      ]
    };
  }

  /**
   * 获取模拟学生学情数据
   * @param {number} courseId - 课程ID
   * @param {number} [classId] - 班级ID，可选
   * @returns {object} - 模拟学生学情数据
   */
  getMockStudentLearningStatus(courseId, classId = null) {
    return {
      courseId,
      classId: classId || 1,
      studentCount: 45,
      averageScore: 78.5,
      passRate: 0.92,
      excellentRate: 0.35,
      weakKnowledgePoints: [
        { id: 1012, name: '1.2 基本原理', averageScore: 65.3 },
        { id: 1021, name: '2.1 技术实现', averageScore: 68.7 }
      ],
      strongKnowledgePoints: [
        { id: 1011, name: '1.1 核心术语定义', averageScore: 85.2 },
        { id: 1022, name: '2.2 案例分析', averageScore: 82.9 }
      ],
      learningStyles: {
        visual: 0.45,
        auditory: 0.3,
        reading: 0.15,
        kinesthetic: 0.1
      }
    };
  }

  /**
   * 获取模拟知识点详情
   * @param {number} knowledgePointId - 知识点ID
   * @returns {object} - 模拟知识点详情
   */
  getMockKnowledgePointDetail(knowledgePointId) {
    const mockData = {
      1011: {
        id: 1011,
        name: '1.1 核心术语定义',
        description: '本节介绍课程中的核心术语和基本概念，建立学科认知框架。',
        importance: 8,
        difficulty: 'medium',
        prerequisites: [],
        relatedPoints: [1012],
        teachingMethods: ['讲解', '讨论', '概念图'],
        commonMisconceptions: ['概念A与概念B的混淆', '对术语C的理解偏差']
      },
      1012: {
        id: 1012,
        name: '1.2 基本原理',
        description: '本节介绍学科的基本原理和理论基础，是后续应用的前提。',
        importance: 9,
        difficulty: 'hard',
        prerequisites: [1011],
        relatedPoints: [1021],
        teachingMethods: ['讲解', '推导', '案例分析'],
        commonMisconceptions: ['原理D的适用范围误解', '公式E的使用条件忽略']
      },
      1021: {
        id: 1021,
        name: '2.1 技术实现',
        description: '本节介绍基本原理的技术实现方法和实践应用。',
        importance: 7,
        difficulty: 'medium',
        prerequisites: [1012],
        relatedPoints: [1022],
        teachingMethods: ['演示', '实验', '项目实践'],
        commonMisconceptions: ['技术F的性能误解', '实现方法G的局限性认识不足']
      },
      1022: {
        id: 1022,
        name: '2.2 案例分析',
        description: '本节通过实际案例分析技术应用的效果和最佳实践。',
        importance: 6,
        difficulty: 'easy',
        prerequisites: [1021],
        relatedPoints: [],
        teachingMethods: ['案例研究', '小组讨论', '报告'],
        commonMisconceptions: ['案例H的特殊性与普遍性混淆']
      }
    };
    
    return mockData[knowledgePointId] || {
      id: knowledgePointId,
      name: `知识点${knowledgePointId}`,
      description: '知识点描述信息',
      importance: 5,
      difficulty: 'medium',
      prerequisites: [],
      relatedPoints: [],
      teachingMethods: ['讲解', '讨论'],
      commonMisconceptions: ['常见误解']
    };
  }

  /**
   * 获取模拟课程教学资源
   * @param {number} courseId - 课程ID
   * @returns {object} - 模拟课程教学资源
   */
  getMockCourseResources(courseId) {
    return {
      courseId,
      resources: [
        {
          id: 201,
          type: 'textbook',
          title: '《课程教材》',
          author: '示例作者',
          publisher: '教育出版社',
          year: 2022,
          url: 'http://example.com/textbook'
        },
        {
          id: 202,
          type: 'slides',
          title: '课程PPT',
          author: '任课教师',
          chapterCount: 12,
          url: 'http://example.com/slides'
        },
        {
          id: 203,
          type: 'video',
          title: '教学视频集',
          author: '任课教师',
          duration: '24小时',
          url: 'http://example.com/videos'
        },
        {
          id: 204,
          type: 'exercise',
          title: '习题集',
          author: '任课教师',
          questionCount: 150,
          url: 'http://example.com/exercises'
        }
      ],
      templates: [
        {
          id: 301,
          type: 'design',
          name: '教案模板',
          description: '标准教案格式，包含教学目标、重难点、过程等',
          url: 'http://example.com/templates/design'
        },
        {
          id: 302,
          type: 'paper',
          name: '试卷模板',
          description: '标准试卷格式，包含选择题、填空题、应用题等',
          url: 'http://example.com/templates/paper'
        }
      ]
    };
  }
}

module.exports = new EduSystemClient();